<!--
 * @Author: 'zhangkeqq' '2211709169@qq.com'
 * @Date: 2025-06-24 16:02:43
 * @LastEditors: your name
 * @LastEditTime: 2025-07-05 16:37:47
 * @FilePath: \vue3-admin\src\views\acl\user\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <!-- 头部搜索 -->
    <el-card>
      <el-form :inline="true">
        <el-row>
          <el-col :span="21">
            <el-form-item label="用户名">
              <el-input v-model="formParamse.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-button type="primary" :disabled="formParamse.username ? false :true" @click="search">搜索</el-button>
            <el-button @click="reset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- table区域 -->
    <el-card style="margin:10px 0">
      <div style="margin-bottom: 10px;">
        <el-button type="primary" @click="changeUser('add',{})">添加</el-button>
        <el-button type="danger" :disabled="selectDelList.length >= 1 ? false :true" @click="delAll">批量删除</el-button>
      </div>
      <el-table :data="tableData" border style="width: 100%;margin-bottom: 10px;"  @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column align="center" prop="" label="#" type="index" width="80" />
        <el-table-column prop="id" label="id" width="80" />
        <el-table-column prop="username" label="用户名字" width="150" />
        <el-table-column prop="name" label="用户角色" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button type="primary" size="small" @click="changeRole(scope.row)">
              <el-icon>
                <User />
              </el-icon>
              分配角色
            </el-button>
            <el-button type="primary" size="small" @click="changeUser('update', scope.row)">
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>
            <el-popconfirm :title="`确定删除${scope.row.username}?`" @confirm="delUser(scope.row)" width="200px">
              <template #reference>
                <el-button size="small" type="danger">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除
                </el-button>
              </template>
            </el-popconfirm>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination @current-change="getDataList" @size-change="sizeChange" v-model:current-page="currentPage"
        v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 10]" background
        layout="prev,pager,next,jumper,-> ,sizes,total" :total="total" />
    </el-card>
    <!-- 添加和编辑的抽屉 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>{{ title }}</h4>
      </template>
      <template #default>
        <div>
          <el-form ref="ruleFormRef" :model="userParams" :rules="rules">
            <el-form-item label="用户姓名" prop="username">
              <el-input v-model="userParams.username" />
            </el-form-item>
            <el-form-item label="用户昵称" prop="name">
              <el-input v-model="userParams.name" />
            </el-form-item>
            <el-form-item v-if="title == '新增用户'" label="用户密码" prop="password">
              <el-input v-model="userParams.password" />
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 分配角色用户的抽屉 -->
    <el-drawer v-model="drawerRole">
      <template #header>
        <h4>分配角色用户</h4>
      </template>
      <template #default>
        <div>
          <el-form>
            <el-form-item label="用户姓名">
              <el-input v-model="userParams.username" disabled  />
            </el-form-item>
          </el-form>
          <el-form-item label="角色列表">
            <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
              全选
            </el-checkbox>
            <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
              <el-checkbox v-for="city in cities" :key="city" :label="city" :value="city">
                {{ city.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelRole">取消</el-button>
          <el-button type="primary" @click="confirmRole">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import { reqUserInfo, reqAddOrUpdateUser, reqDelectUser,reqAllRole,reqSettUserRole,reqSelectUser } from '@/api/acl/user/index'
import type { Records, UserResponseData, User, SetRoleData } from '@/api/acl/user/type'
import type { CheckboxValueType } from 'element-plus'
import { ElMessage } from 'element-plus'
let currentPage = ref<number>(1)
let pageSize = ref<number>(3)
let total = ref<number>(10)
let tableData = ref<Records>([])
let drawer = ref<boolean>(false)
let drawerRole = ref<boolean>(false)
let userParams = reactive<User>({
  id: '',
  username: '',
  name: '',
  password: '',
})
let formParamse = reactive({
  username:'',
})
let selectDelList = ref<any>([])
const ruleFormRef = ref()
let title = ref<string>('')
//获取列表的接口
let getDataList = async () => {
  let res: any = await reqUserInfo(currentPage.value, pageSize.value,formParamse.username)
  if (res.code == 200) {
    tableData.value = res.data.records
    total.value = res.data.total
  }
}
onMounted(() => {
  getDataList()
})
//切换每页条数
let sizeChange = () => {
  currentPage.value = 1
  getDataList()
}
//取消抽屉事件
const cancel = () => {
  drawer.value = false
}
//点击抽屉的确认事件
const confirm = async () => {
  await ruleFormRef.value.validate()//校验成功后才会继续执行
  let res = await reqAddOrUpdateUser(userParams)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: `${title.value == '编辑用户' ? '编辑成功' : '新增成功'}`
    })
    drawer.value = false
    currentPage.value = 1
    getDataList()
  } else {
    ElMessage({
      type: 'error',
      message: `${title.value == '编辑用户' ? '编辑失败' : ' 新增失败'}`
    })
  }

}
// 点击编辑和新增的事件
const changeUser = (type: string, row: User) => {
  // 移除表单校验结果
  nextTick(() => {
    ruleFormRef.value.clearValidate()
  })
  Object.assign(userParams, {
    id: '',
    username: '',
    name: '',
    password: '',
  })
  drawer.value = true
  if (type == 'add') {
    title.value = '新增用户'
  } else {
    title.value = '编辑用户'
    Object.assign(userParams, row)
  }
}

//表单校验
const validatorUserName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户名字至少五位'))
  }
}

const validatorName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户昵称至少五位'))
  }
}

const validatorPassword = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户密码至少六位'))
  }
}

const rules = {
  username: [{ required: true, trigger: 'blur', validator: validatorUserName }],
  name: [{ required: true, trigger: 'blur', validator: validatorName }],
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}
//删除的接口
const delUser = async (row: User) => {
  let res = await reqDelectUser(row.id as number)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    getDataList()
  } else {
    ElMessage({
      type: 'success',
      message: '删除失败'
    })
  }
}
//全选状态
const checkAll = ref(false)
const isIndeterminate = ref(true)
//选中的
const checkedCities = ref([])
//全部的
const cities = ref([])
//点击分配角色用户
const changeRole = async(row: User) => {
  console.log('点击了',row)
  Object.assign(userParams,row)
  let res = await reqAllRole(row.id as number)
  if(res.code == 200){
    cities.value = res.data.allRolesList
    checkedCities.value = res.data.assignRoles
    drawerRole.value = true
  }
  
}

const handleCheckAllChange = (val: CheckboxValueType) => {
  checkedCities.value = val ? cities.value : []
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: CheckboxValueType[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === cities.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < cities.value.length
}

const cancelRole = () => {
  drawerRole.value = false
}
const confirmRole = async() => {
  let data:SetRoleData= {
    userId:userParams.id as number,
    roleIdList:checkedCities.value.map((item)=>{
      return item.id as number
    })
  }
  let res = await reqSettUserRole(data)
  if(res.code == 200){
    ElMessage({
      type: 'success',
      message: '分配职务成功'
    })
      drawerRole.value = false
      getDataList()
  }

}

//搜索
const search = ()=>{
  currentPage.value = 1
  getDataList()
}
//重置
const reset = ()=>{
  Object.assign(formParamse,{
  username:'',
})
  currentPage.value = 1
  getDataList()
}


//多选删除
const handleSelectionChange = (val:User)=>{
  selectDelList.value = val

}
//批量删除
const delAll = async()=>{
  let  idList  = selectDelList.value.map((item:any)=>{
    return item.id
  })
  let res:any =  await reqSelectUser(idList)
  if(res.code == 200){
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    getDataList()
  }

}

</script>

<style scoped></style>